package com.thd.springboottest.security.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


/**
 * com.thd.springboottest.security.utils.ServletUtils
 *
 * @author: wanglei62
 * @DATE: 2022/6/28 10:41
 **/
public class ServletUtils {

    private static ServletUtils instance = null;
    private static ObjectMapper mapper =null;
    static {
        instance  = new ServletUtils();
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //该属性设置主要是将忽略空bean转json错误
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        //忽略在json字符串中存在，在java类中不存在字段，防止错误。
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


        String dateTimepattern = "yyyy-MM-dd HH:mm:ss";
        String datePattern = "yyyy-MM-dd";

        DateFormat dateFormat = new SimpleDateFormat(dateTimepattern);
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.setDateFormat(dateFormat);
    }
    private ServletUtils(){

    }

    public static ServletUtils getInstance(){
        return instance;
    }
    public void success(HttpServletResponse response,Object entity) throws IOException{
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(mapper.writeValueAsString(entity));
    };
    public void failure(HttpServletResponse response,Object entity) throws IOException{
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(mapper.writeValueAsString(entity));

    };




}
